package com.hbnu.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kittychen
 * @since 2025-10-21 17:34
 */
public class ThreadDemo04 implements Runnable {
    private Integer ticket = 20;

    private final Lock lock = new ReentrantLock();

    @Override
    public /* synchronized */ void run() {
        while (true) {
            try {
                lock.lock();   // 加锁
                Thread.sleep(10);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "号票");
                    ticket--;
                } else {
                    break;
                }
                // synchronized (this) {
                //     if (ticket > 0) {
                //         System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "号票");
                //         ticket--;
                //     } else {
                //         break;
                //     }
                // }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();  // 释放锁
            }

        }
    }
}
